package com.atguigu.rwlock;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache
{
    Map<String,String> map = new HashMap<>();


    /*private Lock lock = new ReentrantLock();

    public void write(String key,String value)
    {
        lock.lock();
        try
        {
            System.out.println(Thread.currentThread().getName()+"\t"+"正在写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t"+"完成写入");
        }finally {
            lock.unlock();
        }

    }

    public void read(String key)
    {

        lock.lock();
        try
        {
            System.out.println(Thread.currentThread().getName()+"\t"+"正在读取");
            String result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t"+"完成读取--->: "+result);
        }finally {
            lock.unlock();
        }

    }*/

    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void write(String key,String value)
    {
        rwLock.writeLock().lock();
        try
        {
            System.out.println(Thread.currentThread().getName()+"正在写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"完成写入");
        }finally {
            rwLock.writeLock().unlock();
        }

    }

    public void read(String key)
    {

        rwLock.readLock().lock();
        try
        {
            System.out.println(Thread.currentThread().getName()+"正在读取");
            String result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"完成读取--->: "+result);
        }finally {
            rwLock.readLock().unlock();
        }

    }
}
public class ReadWriteLockDemo
{
    public static void main(String[] args)
    {
        MyCache myCache = new MyCache();


        for (int i = 1; i <=5; i++) {
            int fin = i;
            new Thread(() -> {
                myCache.write(fin +"", fin +"");
            },String.valueOf(i)).start();
        }

        for (int i = 1; i <=5; i++) {
            int fin = i;
            new Thread(() -> {
                myCache.read(fin +"");
            },String.valueOf(i)).start();
        }
    }
}
